package com.shadow.demo.decompilation;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class Step0 {

    private static int INDEX = 1;

    public static void main(String[] args) {
        // 删文件
        test1();
        // 复制整个目录
//        test2();
        // 。。。
//        test3();
    }

    public static void test1() {
        deleteDirectory(Paths.get(Config.RM_DIRECTORY));
    }

    public static void test2() {
        File file = new File(Config.TEST1);
        FileUtils.copyAll(file, new File(Config.TARGET3_DIRECTORY));
    }

    public static void test3() {
        File rootDir = new File(Config.RM_DIRECTORY);
        File file = getLast(rootDir);
        rm(file);
    }

    public static File getLast(File rootDir) {
        if (rootDir.isDirectory()) {
            File[] files = rootDir.listFiles();
            if (files != null && files.length == 1) {
                System.out.println(INDEX++);
                sleep();
                getLast(files[0]);
            }
        }
        return rootDir;
    }

    public static void rm(File rootDir) {
        File parentFile = rootDir.getParentFile();
        boolean delete = rootDir.delete();
        System.out.println(delete);
        if (delete && INDEX > 3000) {
            INDEX--;
            rm(parentFile);
        }
    }

    public static void sleep() {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void deleteDirectory(Path path) {
        if (!Files.exists(path)) {
            System.out.println("目录不存在：" + path);
            return;
        }

        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                // 先删除文件
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                // 再删除空目录
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println("目录及其内容删除成功：" + path);
    }
}
